<?php

/**
 * 干电力API
 */
use qscmslib\passport\gandianli_passport;
use think\Config;

class GdlApi {

    protected $cipher = MCRYPT_RIJNDAEL_128;
    protected $mode = MCRYPT_MODE_ECB;
    protected $pad_method = NULL;
    protected $secret_key = '';
    protected $iv = '';
    protected $error = '';

    /**
     * 连接用户中心
     */
    protected function _user_server()
    {
        $passport = new gandianli_passport('gandianli');
        return $passport;
    }

    /*
     * 公用获取错误信息函数
     */

    public function getError() {
        return $this->error;
    }

    /*
     * 手动过滤函数 想过滤什么自己加1111
     */

    public function strFilter($str) {
        $arr = array('`', '~', '!', '！', '#', '$', '￥', '%', '^', '……', '&', '*', '\\', '[', ']', '、', '?', '？', 'eva', ' ', '	', 'inser', 'updat', 'selec', 'form', '(', ')', '@', 'scrip', '<', '>', 'and', 'or', 'exe', '|', '{', '}');
        $str = str_replace($arr, '', $str);
        return $str;
    }

    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     * @param $type 1不处理直接提交 0为json
     */
    public function request_post($url = '', $ispost = true, $post_data = array(), $type = 0) {
        if (empty($url) || empty($post_data)) {
            return false;
        }

        $o = "";
        $post_data = json_decode($post_data);
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = json_encode($post_data);
        //$post_data = substr($o,0,-1);
        $key = md5(base64_encode($post_data));
        if ($ispost) {
            $url = $url;
        } else {
            $url = $url . '?' . $post_data;
        }

        if ($type) {
            $curlPost = $post_data;
        } else {
            $curlPost = ['key' => $post_data, 'ngis' => md5($post_data . 'as')];
        }
        header("Content-type: text/html; charset=utf-8");
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url); //抓取指定网页
        curl_setopt($ch, CURLOPT_REFERER, 'http://gdl.gandianli.com/');
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_TIMEOUT, 3); //设置3秒钟 如果3秒没有返回直接丢失
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        }
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }

    /*     * ***aes 加密***** */

    public function set_cipher($cipher) {
        $this->cipher = $cipher;
    }

    public function set_mode($mode) {
        $this->mode = $mode;
    }

    public function set_iv($iv) {
        $this->iv = $iv;
    }

    public function set_key() {
        $this->secret_key = SECRET_KEY;
    }

    public function require_pkcs5() {
        $this->pad_method = 'pkcs5';
    }

    protected function pad_or_unpad($str, $ext) {
        if (is_null($this->pad_method)) {
            return $str;
        } else {
            $func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
            if (is_callable($func_name)) {
                $size = mcrypt_get_block_size($this->cipher, $this->mode);
                return call_user_func($func_name, $str, $size);
            }
        }
        return $str;
    }

    protected function pad($str) {
        return $this->pad_or_unpad($str, '');
    }

    protected function unpad($str) {
        return $this->pad_or_unpad($str, 'un');
    }

    public function encrypt($str) {
        $this->set_key();
        $str = $this->pad($str);
        $td = mcrypt_module_open($this->cipher, '', $this->mode, '');

        if (empty($this->iv)) {
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        } else {
            $iv = $this->iv;
        }

        mcrypt_generic_init($td, $this->secret_key, $iv);
        $cyper_text = mcrypt_generic($td, $str);
        $rt = base64_encode($cyper_text);
        //$rt = bin2hex($cyper_text);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);

        return $rt;
    }

    public function decrypt($str) {
        $this->set_key();
        $td = mcrypt_module_open($this->cipher, '', $this->mode, '');

        if (empty($this->iv)) {
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        } else {
            $iv = $this->iv;
        }

        mcrypt_generic_init($td, $this->secret_key, $iv);
        //$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
        $decrypted_text = mdecrypt_generic($td, base64_decode($str));
        $rt = $decrypted_text;
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);

        return $this->unpad($rt);
    }

    public static function hex2bin($hexdata) {
        $bindata = '';
        $length = strlen($hexdata);
        for ($i = 0; $i < $length; $i += 2) {
            $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
        }
        return $bindata;
    }

    public static function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    public static function pkcs5_unpad($text) {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text))
            return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
            return false;
        return substr($text, 0, -1 * $pad);
    }

    /*     * ***aes 加密**** */

    public function arrayToXml($arr) {//转xml
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    public function xmlToArray($xml) {    //xml 转回数组
        //禁止引用外部xml实体
        try {
            libxml_disable_entity_loader(true);
            $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            return $values;
        } catch (Exception $e) {
            return false;
        }
    }

    public function gandianli_url() {
        return Config::get('gdlapi.API_URL');
    }

    public function disemDark($args) {
        $post_data = [
            'username' => $args['username'],
            'password' => $args['userpassword'],
            'phone' => $args['phone'],
            'type' => 'user',
        ];
        $url = self::gandianli_url();
        $gandianli = self::request_post($url, 1, json_encode($post_data));
        $gandianli = json_decode($gandianli, true);
        if (empty($gandianli['username']))
            return $gandianli; //没有就直接不往下执行了
        $gandianli['password2'] = $args['userpassword'];
        if (false === self::gandianli_to_local_sync($gandianli)) {
            return false;
        }
        return $gandianli;
    }

    public function reg_send_sms($args) {
        $post_data = [
            'mobile' => $args,
            'type' => 'reg_send_sms',
        ];
        $url = self::gandianli_url();
        $gandianli = self::request_post($url, 1, json_encode($post_data));
        $gandianli = json_decode($gandianli, true);
        if (empty($gandianli['username']))
            return $gandianli; //没有就直接不往下执行了
        $gandianli['password2'] = $gandianli['password'];
        if (false === self::gandianli_to_local_sync($gandianli)) {
            return false;
        }
        return $gandianli;
    }

    public function inquiry($username) {
        $user = M('members')->field('*')->where("username='{$username}'")->find();
        return $user;
    }

    /*
     * 修改密码
     * pwd 需要修改的密码 明文
     * oldpwd 用户表的原始密码
     * has 扩展码
     * uid 用户id
     *
     */

    public function changePassword($pwd, $oldpwd, $has, $uid) {
        $new_pwd = D('Members')->make_md5_pwd($pwd, $has);
        print_r($pwd . '----' . $has);
        die;
        if ($oldpwd != $new_pwd) {
            $data['password'] = $new_pwd;

            M("Members")->where("uid='{$uid}'")->save($data);
        }
    }

    public function gandianli_to_local_sync($args) {//用于骑士的注册
        $post_data['reg_type'] = 3;
        $data = array(
            'username' => $args['username'],
            'password' => $this->strFilter($args["password2"]),
            'email' => $args["email"] ? $args["email"] : $args['username'] . $args["mobile"] . '@gandianli.com',
            'mobile' => $args["mobile"],
            'utype' => $args['groupid'] == 5 ? 2 : 1,
            'reg_type' => $post_data['reg_type'],
            'mobile_audit' => $args["vmobile"],
            'email_audit' => $args["vemail"],
            'pwd_hash' => $args["passsalt"]
        );



        /* 完成在人才网同步流程 */
        $passport = $this->_user_server();
        $result = $passport->user_local_sync($data);
        $uid = is_array($result) ? $result['uid'] : $result;
        if ($uid && $data['utype'] == '1') {

            /*             * 录入公司信息 */
            $com_setarr['uid'] = $uid;
            $com_setarr['audit'] = $args["vcompany"];
            $company_mod = D('CompanyProfile');
            $company = $company_mod->field('id,companyname')->where(array('uid' => $uid))->find();

            if (!empty($company)) {
                $com_setarr['id'] = $company['id'];
                if (false === $company_mod->save($com_setarr)) {
                    $this->error = '更新公司信息失败！';
                    return false;
                }
            } else {
                $com_setarr['email'] = $args["email"];
                $com_setarr['companyname'] = $args["company"];
                $com_setarr['contact'] = $args["truename"];
                $com_setarr['telephone'] = $args["mobile"];
                $com_setarr['address'] = $args["address"];
                //$com_setarr['nature_cn'] = $args['type'];
                //$com_setarr['landline_tel']='';
                $com_setarr['contact_show'] = 1;
                $com_setarr['user_status'] = 1;
                $com_setarr['addtime'] = time(); //注册时间
                $com_setarr['refreshtime'] = time(); //刷新时间
                $com_setarr['telephone_show'] = 1; //刷新时间
                $com_setarr['landline_tel_show'] = 1; //刷新时间
                $com_setarr['qq'] = 0; //刷新时间

                if (false === $insert_company_id = $company_mod->add($com_setarr)) {
                    $this->error = '新增加公司信息失败！';
                    return false;
                }
                $data['uid'] = $uid;
                $uid && D('Members')->user_register($data);
            }
        } else {
            //$this->error = '您的帐号激活失败!，请联系客服！';
            //return false;
        }
        return true;
    }

    public function modify($args) {//修改密码
        /* $post_data = [
          'username'=>$args["username"],
          'org_username'=>$args["username"],
          'special'=>12,
          'oldpassword'=>$args['password'],
          'password'=>$args['password'],
          'type'=>'modify',
          ]; */
        $post_data = $args;
        $post_data['type'] = 'modify';
        $post_data['oldpassword'] = $args['oldpassword'];
        $post_data['special'] = 'aaada';
        $url = self::gandianli_url();
        $gandianli = self::request_post($url, 1, json_encode($post_data));
        $gandianli = json_decode($gandianli, true);
        $this->error = $gandianli['mark'];
        return $gandianli['status'];
    }

    public function repeat($args, $type) {//验证是否重复
        $post_data = [
            'username' => $args,
            'staues' => $type,
            'type' => 'repeat',
        ];
        $url = self::gandianli_url();
        $gandianli = self::request_post($url, 1, json_encode($post_data));
        $uid = json_decode($gandianli, true);
        return $uid;
    }

    public function regist_gandian($args, $com_info = NULL) {//直接注册 这里是模拟提交 到干电力直接注册
        !empty($args['utype']) && $groupid = $args['utype'] == 1 ? 6 : 5;
        $post_data = [
            'username' => $args['username'],
            'truename' => empty($com_info['contact']) ? $args['username'] : $com_info['contact'],
            'password' => $args['password'],
            'mobile' => empty($args['mobile']) ? $args['telephone'] : $args['mobile'],
            'groupid' => $groupid,
            'type' => 'registered',
            'reg_type' => $args['reg_type'],
        ];
        if (!empty($args['utype']) && $args['utype'] == 1) {
            $post_data['company']['companyname'] = $com_info['companyname'];
            $post_data['company']['telephone'] = $com_info['landline_tel'];
        }
        $url = self::gandianli_url();
        $result = self::request_post($url, 1, json_encode($post_data));
        $result = json_decode($result, true); //返回1代表注册成功				
        return $result;
    }

}
